<?php 
namespace User\Controller;
use Common\Controller\BaseController;
class LoginController extends BaseController{
	
	function _initialize() {
		//登录拦截，防止已经登录的再登录
		if($_SESSION['loginUser'] && ACTION_NAME != 'logout'){
			redirect('/user/setting.html'); //拦截到登录
			exit();
		}
	}
	
	
	/**
	 * 登录页面
	 */
	public function index(){
		$next = I('get.next');
		if(!$next){
			$url = '/user/login?next='.urlencode($this->getgoto());
			header("location:".$url);
			exit();
		}else{
			session('goto',$next);
		}
		$this->display();
	}
	
	/**
	 * 执行登录
	 */
	public function login_post(){
		
		
		$this->_check_token('login',$_REQUEST['token']);
		
		if(!I('username') || !I('password')){
			_apiReturn(0, L('error_info_login_1'));
		}
		
		$m = D('Users');
		
		$map['username|email|mobile'] = I('username');
		$temp = $m->where($map)->find();
		if(!$temp){
			_apiReturn(0, "用户名不存在");
		}
		
		$map['password'] = md5(I('password'));
		$map['status'] = array('neq',0); //状态不能为0
		$user = $m->where($map)->find();
		if(!$user){
			_apiReturn(0, '密码输入错误',$data,$url);
		}
		if($user['status'] == '-1'){
			_apiReturn(0, '该账户已被禁用',$data,$url);
		}
		if(!$user['role']){
			_apiReturn(0, '非培训账号无法登录',$data,$url);
		}
		
		if($user){
			//登录成功
			token_del('login'); //删除表单指令
			D('UserLog')->_add($user['uid'],'login','登录平台'); //写入日志
			
			//生成session
			unset($user['password']);
			unset($user['create_time']);
			unset($user['update_time']);
			$_SESSION['loginUser'] = $user;
			
			if(session('goto')){
				$url = session('goto');
				session('goto',null);
			}else{
				$url = "/";
			}
			
			_apiReturn(1, L('login').L('success'),$data,"/admin/index/index.html");
		}else{
			//检测一下是不是状态为0的用户
			$map['status'] = 0;
			$user = $m->where($map)->find();
			if($user){
				$_SESSION['tmpUser'] = $user; //存储在tmpUser session里面
				_apiReturn(0,'The account has not yet been activated','','/user/reg/regnext?type=email'); //去激活
			}
			_apiReturn(0, L('login').L('failed'));
		}
		
		
	}
		
	/**
	 * 登出
	 */
	public function logout(){
		if($_SESSION['loginUser']){
			D('UserLog')->_add($_SESSION['loginUser']['uid'],'logout','登出平台'); //写入日志
			$_SESSION['loginUser'] = null;//销毁session
			unset($_SESSION['loginUser']);
		}
		redirect('/'); //返回首页
		exit();
	}
	
	/**
	 * 获取返回地址
	 */
	protected function getgoto(){
		$goto = $_SERVER['HTTP_REFERER'];
		$host = 'http://'.$_SERVER['HTTP_HOST'];
		if(!$goto){
			$goto = $host;
		}
		//地址过滤
		$guolvs = array('/Users/login','/Users/register','/Users/resetpwd','/Users/Member');
	
		foreach($guolvs as $gl){
			if(strpos($goto, $gl)){
				$goto =  $host;
				break;
			}
		}
		return $goto;
	}
}
?>